<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Model\Contract;
use App\Model\DownHistory;
use App\Model\Member;
use App\Model\Order;
use App\Model\OrderType;
use App\Model\Special;
use App\Model\MemberCoupon;
use App\Services\PaymentStrategyFactory;
use http\Env\Request;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\ViewEngine\Contract\FactoryInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use RedisException;
use Trait\ResponseMsg;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use Yansongda\Pay\Pay;

/**
 *
 */
class OrderPayController extends AbstractController
{
    use ResponseMsg;

    protected array $config;

    protected Redis $redis;

    #[Inject]
    protected Member $member;

    #[Inject]
    protected Order $order;

    public function __construct(RequestInterface $request)
    {
        $this->redis = container()->get(Redis::class);
    }

    /**支付-通用
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function pay(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $params = $request->inputs(['payid', 'receiving', 'contract_id','return_url',
            'coupon_id', 'userid', 'planid', 'unitid', 'keywordid', 'bd_vid','code',
            'keyword', 'type', 'type_mode','price','special_id','host']);
        if (!isset($params['type_mode']) || !isset($params['type'])) {
            $this->error(ErrorCode::OPTION_ERR);
        }
        $payModel = PaymentStrategyFactory::createPaymentStrategy($params['type'], $request);
        $ret = $payModel->pay($params);
        if ($ret['code'] == 200) {
            return $this->success($ret);
        }
        return $this->error(code: $ret['code']);
    }

    /**立即支付
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function payNow(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $params = $request->inputs(['order_no','coupon_id','code','return_url','type','type_mode','host']);
        if (!isset($params['order_no'])) {
            $this->error(ErrorCode::OPTION_ERR,msg:'缺失订单id');
        }
        $payModel = PaymentStrategyFactory::createPaymentStrategy($params['type'], $request);
        $ret = $payModel->payNow($params);
        if ($ret['code'] == 200) {
            return $this->success($ret);
        }
        return $this->error(code: $ret['code']);
    }


    /**微信-根据订单号获取二维码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function qrCode(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $params = $request->inputs(['coupon_id', 'order_no']);
        if(!isset($params['order_no'])){
            return $this->error(ErrorCode::OPTION_ERR);
        }
        $payModel = PaymentStrategyFactory::createPaymentStrategy('wechat', $request);
        $ret = $payModel->qrCode($params);
        if($ret['code'] == 200){
            return $this->success($ret);
        }
        return $this->error(code: $ret['code'],msg: isset($ret['message'])?$ret['message']:'');
   }

    /**微信支付回调
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function wxNotifyCallback(RequestInterface $request)
    {
        $payModel = PaymentStrategyFactory::createPaymentStrategy('wechat', $request);
        $payModel->notify();
    }

    /**支付宝支付回调
     * @param RequestInterface $request
     * @return void
     */
    public function aliNotifyCallback(RequestInterface $request)
    {
        $payModel = PaymentStrategyFactory::createPaymentStrategy('alipay', $request);
        $payModel->notify();
    }

    /**查询
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkStatus(RequestInterface $request):\Psr\Http\Message\ResponseInterface{
        $order_params = $request->input('order_no');
        $order_no  = explode('-', $order_params);
        $order_no = $order_no[0];
        if(!$order_no){
            return $this->error(ErrorCode::ORDER_NOT_FOUND);
        }
        $orderModel = $this->order->where('order_no',$order_no)->first();
        if(!$orderModel){
            return $this->error(ErrorCode::ORDER_NOT_FOUND);
        }
        $data['status'] = $orderModel->status;
        $data['type'] = 1;
        if($orderModel->type == OrderType::ONE_TYPE){
           $data['type'] = 4;
//            $data['data'] = Contract::where('id',$orderModel->contract_id)->first(['id','title','path','title_pic']);
        }
        return $this->success($data);
    }

    /**取消订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cancelOrder(RequestInterface $request):ResponseInterface{
        $order_no = $request->input('order_no');
        if(!$order_no){
            return $this->error(msg:'订单号参数错误');
        }
        $member = $this->member->getInfo($request);
        if (!$member) {
            return $this->error(code:ErrorCode::UNKNOW_INFO,msg:'请先登陆');
        }
        $orderModel = $this->order->where('order_no',$order_no)->first();
        if(!$orderModel){
            return $this->error(msg:'订单不存在');
        }
        if($orderModel->status != 0){
            return $this->error(msg:'订单状态不可取消');
        }
        if($orderModel->member_coupon_id){
           MemberCoupon::where('id',$orderModel->member_coupon_id)->update(['status'=>1]);
        }
        if($member['id']  != $orderModel->member_id){
            return $this->error(msg:'操作繁忙稍后重试');
        }
        $orderModel->status = Order::CANCEL;
        $orderModel->save();
        if($orderModel->pay_type == Common::ORDER_WX_PAY){
            $order_no = $orderModel->order_no.'-'.$orderModel->version ;
            $payModel = PaymentStrategyFactory::createPaymentStrategy('wechat', $request);
            $payModel->cancel($order_no);
        }else{
            $order_no = $orderModel->order_no;
            $payModel = PaymentStrategyFactory::createPaymentStrategy('alipay', $request);
            $payModel->cancel($order_no);
        }
       return $this->success(msg:'取消成功');
    }


    /**单次购买获取文件路径
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getOrderPath(RequestInterface $request):ResponseInterface
    {
        $order = $request->input('order');
        $order = explode('-', $order);
        $order = $order[0];
        if (!$order) {
            return $this->error(code:ErrorCode::PARAMS_ERR,msg:'参数错误');
        }
        $order = Order::where(function ($query) use ($order) {
            $query->where('order_no', $order);
            $query->orWhere('out_trade_no', $order);
        })->first();
        if (!$order) {
            return $this->error(code:ErrorCode::ORDER_NOT_FOUND,msg:'订单不存在');
        }
        if ($order->status != Order::PAYED) {
            return $this->error(code:ErrorCode::ORDER_NOT_PAY,msg:'订单未支付');
        }
        if($order->type == OrderType::SPECIAL){
            $data= Special::where('id',$order->special_id)->first();
            $save['special_id']  = $order->special_id;
        }else{
            $data = Contract::where('id', $order->contract_id)->first();
            $save['contract_id'] = $order->contract_id;
        }
        $member = $this->member->getInfo($request);
        if(!$member){
            $member['id'] = 0;
        }
        $save['member_id'] =$member['id'];
        $save['type']  = $order->type;
        DownHistory::create($save);
        $data['order'] = $order;
        $data['path'] = '//cdn.mihetong.com/'.$data['path'];
        return $this->success($data);
    }

    public function canCouponList(RequestInterface $request):ResponseInterface{
        $orderId = $request->input('orderId');
        $member = $this->member->getInfo($request);
        $orderData = $this->order->where('id',$orderId)->first();
        if(!$member || !$orderData  || $orderData->type != OrderType::NORMAL_TYPE){
            return $this->success(array());
        }
        try{
            $now = time();
            $couponArr = Db::table('member_coupon as m')
                ->leftJoin('coupon as c' ,'m.coupon_id','=','c.id')
                ->where('m.member_id',$member['id'])
                ->where('m.start','<',$now)
                ->where('m.end','>',$now)
                ->where('m.status',MemberCoupon::NORMAL)
                ->select('m.*','c.days','c.title','c.price','c.fill_price')
                ->where('c.fill_price','<=',$orderData->money)
                ->orderBy('c.price')
                ->get();
            return $this->success($couponArr);
        }catch (\Exception $e){
            return $this->success(array());
        }
    }




}
